package cn.gztang.util;

import cn.gztang.constant.ErrorCode;
import cn.gztang.exception.InvalidRequestParamException;
import cn.gztang.exception.NullRequestParamException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.Collection;
import java.util.List;

/**
 * @author GaoFeng2017
 * @date 2018/7/13 11:17
 */
public class ValidateUtil {

    private static final String[] provinces = "北京市,天津市,上海市,重庆市,河北省,山西省,辽宁省,吉林省,黑龙江省,江苏省,浙江省,安徽省,福建省,江西省,山东省,河南省,湖北省,湖南省,广东省,海南省,四川省,贵州省,云南省,陕西省,甘肃省,青海省,内蒙古自治区,广西壮族自治区,西藏自治区,宁夏回族自治区,新疆维吾尔自治区".split(",");

    public static void checkArrayParam(Object[] objs) {
        if (isEmptyArray(objs)) {
            throw new NullRequestParamException("请求参数不能为空", ErrorCode.NULL_REQUEST_PARAM);
        }
    }

    public static boolean isEmptyArray(Object[] objs) {
        return objs == null || objs.length == 0;
    }

    public static void checkRequestParam(BindingResult result) {
        List<ObjectError> allErrors = result.getAllErrors();
        if (result.hasErrors()) {
            throw new InvalidRequestParamException(allErrors.get(0).getDefaultMessage(), ErrorCode.INVALID_REQUEST_PARAM);
        }
    }

    public static boolean checkCollection(Collection collection) {
        return collection != null && !collection.isEmpty();
    }


    public static void checkSingleParam(Object param) {
        if (isNull(param)) {
            throw new InvalidRequestParamException("非法的请求参数", ErrorCode.INVALID_REQUEST_PARAM);
        }
    }

    public static boolean isNull(Object param) {
        return param == null;
    }

    public static byte booleanValue(boolean flag) {
        return (byte) (flag ? 1 : 0);
    }


    public static void checkKey(Integer key) {
        if (key <= 0) {
            throw new InvalidRequestParamException("非法的请求参数",ErrorCode.INVALID_REQUEST_PARAM);
        }
    }

    public static void checkAccess(byte userType, byte... type) {

        for (byte b : type) {
            if (userType == b) {
                return;
            }
        }

        throw new InvalidRequestParamException("权限不足,访问失败",ErrorCode.TYPE_MISMATCHING);

    }
}
